document.addEventListener("DOMContentLoaded", function () {
    // 获取每个菜单的按钮和对应的菜单内容
    const toggleUserButton = document.getElementById('toggle-user');
    const toggleDormButton = document.getElementById('toggle-dorm');
    const toggleBuildingButton = document.getElementById('toggle-building');
    const toggleAllocateButton = document.getElementById('toggle-allocate');
    const toggleMeterButton = document.getElementById('toggle-meter');

    const userMenu = document.getElementById('user-menu');
    const dormMenu = document.getElementById('dorm-menu');
    const buildingMenu = document.getElementById('building-menu');
    const allocateMenu = document.getElementById('allocate-menu');
    const meterMenu = document.getElementById('meter-menu');

    // 读取存储的菜单状态
    const menuState = JSON.parse(localStorage.getItem('menuState')) || {};

    // 设置菜单的初始状态
    if (menuState.userMenu) userMenu.classList.add('open');
    if (menuState.dormMenu) dormMenu.classList.add('open');
    if (menuState.buildingMenu) buildingMenu.classList.add('open');
    if (menuState.allocateMenu) allocateMenu.classList.add('open');
    if (menuState.meterMenu) meterMenu.classList.add('open');

    // 关闭所有菜单
    function closeAllMenus() {
        userMenu.classList.remove('open');
        dormMenu.classList.remove('open');
        buildingMenu.classList.remove('open');
        allocateMenu.classList.remove('open');
        meterMenu.classList.remove('open');
    }

    // 更新菜单状态并存储
    function updateMenuState() {
        const newState = {
            userMenu: userMenu.classList.contains('open'),
            dormMenu: dormMenu.classList.contains('open'),
            buildingMenu: buildingMenu.classList.contains('open'),
            allocateMenu: allocateMenu.classList.contains('open'),
            meterMenu: meterMenu.classList.contains('open'),
        };
        localStorage.setItem('menuState', JSON.stringify(newState));
    }

    // 为每个菜单项添加点击事件监听器
    toggleUserButton.addEventListener('click', function () {
        closeAllMenus();  // 关闭其他菜单
        userMenu.classList.toggle('open');  // 切换当前菜单的显示状态
        updateMenuState();  // 更新状态
    });

    toggleDormButton.addEventListener('click', function () {
        closeAllMenus();  // 关闭其他菜单
        dormMenu.classList.toggle('open');  // 切换当前菜单的显示状态
        updateMenuState();  // 更新状态
    });

    toggleBuildingButton.addEventListener('click', function () {
        closeAllMenus();  // 关闭其他菜单
        buildingMenu.classList.toggle('open');  // 切换当前菜单的显示状态
        updateMenuState();  // 更新状态
    });

    toggleAllocateButton.addEventListener('click', function () {
        closeAllMenus();  // 关闭其他菜单
        allocateMenu.classList.toggle('open');  // 切换当前菜单的显示状态
        updateMenuState();  // 更新状态
    });

    toggleMeterButton.addEventListener('click', function () {
        closeAllMenus();  // 关闭其他菜单
        meterMenu.classList.toggle('open');  // 切换当前菜单的显示状态
        updateMenuState();  // 更新状态
    });
});
